/*
 * ArrayOrdened.c
 *
 *  Created on: 21/01/2012
 *      Author: marcio
 */

#include "ArrayOrdened.h"

ArrayOrdened* arrayordened_newArray(long size, int (*function)(void*, void*)){
	ArrayOrdened* ao = malloc(sizeof(ArrayOrdened));
	ao->size = size > 0? size: 0;
	ao->compare = function;
	ao->elem = malloc(sizeof(void*)*ao->size);
	return ao;
}

void* arrayordened_getElem(ArrayOrdened* a, long i){
	return i < a->size && i > -1 ? a->elem[i]: NULL;
}

int arrayordened_putElem(ArrayOrdened* a, void* newElem){
	if(newElem == NULL) return -1;
	int i;
	int ret;
	int keep = 1;
	void* aux, aux2;
	while(keep >= 0){
		keep = compare(a->elem[i++], elem);
	}
	ret = i;
	if(ret > a->size) return -1;
	aux = a->elem[i];
	a->elem[i++] = newElem;
	for(; i < a->size; i++ ){
		aux2 = a->elem[i];
		a->elem[i] = aux;
		aux = aux2;
	}
	return ret;
}

int arrayordened_isEmpty(ArrayOrdened* a){
	int i;
	for(i = 0 ; i < a->size; i++){
		if(a->elem[i] != NULL) return 0;
	}
	return 1;
}

int arrayordened_searchFor(ArrayOrdened* a, void* elem){
	int i = 0;
	int keep = 1;
	while(keep > 0){
		keep = compare(a->elem[i++], elem);
	}
	if(keep == 0) return i;
	return -1;
}

int arrayordened_delete(ArrayOrdened* a){
	int i = 0;
	for(i = 0; i < a->size; i++){
		if(a->elem[i] != NULL)free(a->elem[i]);
	}
	free(a->elem);
	return free(a);
}
